<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\cache\TheRedis;
use app\common\enum\RedisKeyEnum;
use app\common\exception\ExceptionEmun;
use app\common\exception\SystemException;
use app\common\exception\TokenException;
use app\common\exception\UserException;
use app\common\token\Token;
use think\facade\Request;

/**
 * 校验Token监听
 * Class VerifyToken
 * @package app\listener
 */
class VerifyToken
{
    /**
     * 事件监听处理
     * @return mixed
     */
    public function handle()
    {
        //验证token
        $header = Request::instance()->header();
        $module = app('http')->getName();
        //token名多样化
        $token_name = sprintf("%s-%s", $module, "token");
        if (!empty($header[$token_name])) {
            Token::instance()->verifyToken($header[$token_name]);
        } elseif (!empty($header['authkey'])) {
            Token::instance()->verifyToken($header['authkey']);
        } else {
            ExceptionEmun::throwException(TokenException::ILLEGAL_TOKEN);
        }
        //验证登录缓存
        $user = Token::instance()->getUserInfo();
        $user_id = $user[$user->getPk()];
        $key = TheRedis::composite_cache_key(RedisKeyEnum::LOGIN_USER_IDS, sprintf("%s-%s", $module, "system"));
        $valid = cache($key);
        if (empty($valid) || empty($valid[$user_id])) {
            ExceptionEmun::throwException(SystemException::RELOGIN);
        }
        // 检查账号有效性
        if ($user['status'] != 1) {
            ExceptionEmun::throwException(UserException::LOCKED);
        }
        return TRUE;
    }
}
